from inqueue import app, login_manager
from flask.ext.login import logout_user, login_required, login_user, current_user
from flask import url_for, render_template, redirect, request, flash, g, session
from inqueue.forms import *
from inqueue.models import *
from datetime import *
from sqlalchemy import event
from inqueue.mail.multipartmail import MultipartMail, SMS


##########################################
# Begin Login Stuff
##########################################

login_manager.login_view = "/login"

@login_manager.user_loader
def load_user(userid):
  return User.query.get(userid)

@app.route("/login", methods=["GET", "POST"])
def login():
  form = LoginForm(request.values)
  if request.method == "POST":
    user = db.session.query(User).filter(User.email == form.email.data).first()
    if user and user.password == form.password.data:
      login_user(user, remember=True)
      flash("Logged in successfully","success")
    else:
      flash("Unrecognized username or password combination", "error")
    return redirect(url_for("index"))
  else:
    form = LoginForm()
    reform = RegisterForm()
    return render_template("login.html", form=form, reform = reform)

@app.route("/logout")
def logout():
  logout_user()
  flash("Logged out successfully", "success")
  return redirect(url_for('index'))

@app.route("/register", methods=["GET", "POST"])
def register():

  form = RegisterForm(request.values)
  if request.method == "POST":
    email = form.email.data
    password = form.password.data
    name = form.name.data

    new_user = User(email=email, name = name, password=password)
    new_user.save()
    login_user(new_user)
    flash("Registered successfully", "success")
    return redirect(url_for('index'))
  else:
    return render_template('register.html', form=form)


##########################################
# End Login Stuff
##########################################

@app.route('/')
def index():
  current_tab = 'home'
  if not current_user.is_active():
    return redirect(url_for('login'))
  else:
    pending_orders = current_user.pending_and_ready_orders() if current_user.is_active() else None
    shortest_queue = MenuItem.shortest_queue()
    most_ordered = MenuItem.most_ordered()
    lowest_stock = MenuItem.least_remaining()
    return render_template("index.html", current_tab = current_tab, pending_orders = pending_orders,
                            user = current_user, shortest_queue=shortest_queue, most_ordered=most_ordered,
                            lowest_stock=lowest_stock)


@app.route('/trucks')
def trucks():
  current_tab = 'trucks'
  all_trucks = db.session.query(Truck).all()
  return render_template("trucks.html",all_trucks = all_trucks, current_tab = current_tab)


@app.route('/order/<int:order_id>')
def order_detail(order_id):
  order = db.session.query(Order).get(order_id)
  return render_template("order_detail.html", order = order)

@app.route('/settings')
@login_required
def settings():
  current_tab = 'settings'
  truck_id = None
  truck = db.session.query(Truck).filter(Truck.user_id == current_user.id).first()
  if truck:
    truck_id = truck.id
  return render_template("settings.html", current_tab = current_tab, truck_id = truck_id, current_user = current_user)

@app.route('/trucks/<int:truck_id>')
def truck_detail(truck_id):
  current_tab = 'trucks'
  truck = db.session.query(Truck).filter(Truck.id == truck_id).first()
  menu = truck.menu_for_day(datetime.date(datetime.now()))
  order_form = PlaceOrderForm(request.values)

  return render_template("truck_view.html", current_tab = current_tab, truck = truck, menu = menu,order_form = order_form)


@app.route('/order/<int:menu_item_id>', methods = ['POST'])
@login_required
def place_order(menu_item_id):

  order_form = PlaceOrderForm(request.values)
  quantity = order_form.quantity.data
  menu_item = db.session.query(MenuItem).get(menu_item_id)
  if menu_item.remaining_orders() > 0:
    new_order = Order(user_id=current_user.id, menu_item_id=menu_item_id, time_created=datetime.utcnow(), quantity=quantity)
    new_order.save()
    flash("Order placed", "success")
  else:
    flash("Error placing order", "error")
  return redirect(url_for('order_detail',order_id = new_order.id))

@app.route('/order/<int:order_id>/completed')
def mark_order_completed(order_id):
  order = db.session.query(Order).get(order_id)
  order.mark_completed()
  return redirect(url_for('admin_index'))

@app.route('/order/<int:order_id>/ready')
def mark_order_ready(order_id):
  order = db.session.query(Order).get(order_id)
  order.mark_ready()
  return redirect(url_for('admin_index'))

@app.route('/admin_index')
@login_required
def admin_index():
  print current_user.id
  truck = Truck.query.filter(current_user.id == Truck.user_id).first()
  if not truck:
    flash("Page reserved for truck owner")
    return redirect(url_for('index'))
  active_orders = truck.get_active_orders()
  ready_orders = truck.get_ready_orders()
  completed_orders = truck.get_completed_orders()
  return render_template('admin_index.html', active_orders=active_orders,
                                             ready_orders=ready_orders,
                                             completed_orders=completed_orders)


@app.route('/admin_remove_menu_item/<int:menu_item_id>')
@login_required
def admin_remove_menu_item(menu_item_id):
  return redirect(url_for('admin_add_food'))

@event.listens_for(Order, "after_insert")
def notify_new_order(mapper, connection, order):
  text = "You placed an order at {0} for a {1}. \
          Go to {2} to view your order \
          updates. Order# {3}".format(order.menu_item.truck.name, order.menu_item.food.name,\
                                      url_for('order_detail', order_id=order.id, _external=True), \
                                      order.id)
  user = order.user
  sms = SMS.get_sms_email(user.phone, user.carrier)
  msg = MultipartMail(recipients=[user.email, sms], subject="Your foodtruck order", text_body=text, html_body=text)
  msg.send()


@event.listens_for(Order.status, "set")
def notify_order_status_change(order, new_status, old_status, __):
  if new_status == Order.STATUS_READY:
    text = "Your order from {0} is ready! \
            Bring your ticket at {1} to the \
            foodtruck to pick up. Order# {2}".format(order.menu_item.truck.name, url_for('order_detail', order_id=order.id, _external=True), order.id)
    user = order.user
    sms = SMS.get_sms_email(user.phone, user.carrier)
    msg = MultipartMail(recipients=[user.email, sms], subject="Your order is ready!", text_body=text, html_body=text)
    msg.send()

@app.route('/change_preferences', methods=["GET", "POST"])
@login_required
def change_preferences():
  current_tab = "settings"
  form = ChangePreferencesForm(request.values)
  if request.method == "POST":

    new_email = form.email.data
    new_password = form.password.data
    new_carrier = form.carrier.data
    new_phone = form.phone.data

    if new_email is not None:
      current_user.email = new_email
    if new_password is not None:
      current_user.password = new_password
    if new_carrier is not None:
      current_user.carrier = new_carrier
    if new_phone is not None:
      current_user.phone = new_phone

    if new_email or new_password or new_carrier or new_phone: # if something changes
      db.session.commit()
      flash("Changes were submitted", "success")

    return redirect(url_for('change_preferences'))
  else:
    return render_template('change_preferences.html', form=form, current_user = current_user, current_tab = current_tab)


@app.route('/admin_add_menu_item', methods = ["GET", "POST"])
@login_required
def admin_add_menu_item():
  form = AddMenuItemForm(request.values)

  if request.method == "POST":
    food_name = form.food_name.data
    food_quantity = form.max_quantities.data
    truck = db.session.query(Truck).filter(Truck.user_id == current_user.id).one()
    if truck:
      new_food = Food(name=food_name, description="")
      new_food.save()
      MenuItem(truck_id=truck.id, date=datetime.date(datetime.utcnow()), food_id=new_food.id, max_quantity=food_quantity).save()
      flash("Menu item added", "success")
      return redirect(url_for('admin_add_menu_item'))
    else:
      flash("You don't have permission to add menu", "error")
      return redirect(url_for('index'))
  else:
    removeForm = RemoveMenuItemForm(request.values)
    exform = AddExistingFoodToMenu(request.values)
    truck = db.session.query(Truck).filter(Truck.user_id == current_user.id).one()
    if truck:
        all_my_food = truck.all_my_food()
        current_menu = truck.menu_for_day(datetime.date(datetime.utcnow()))
        return render_template('admin_add_food.html', all_my_food=all_my_food, current_menu=current_menu, form = form,removeForm = removeForm,exform = exform)
    else:
        flash("You don't have permission to add menu", "error")
        return redirect(url_for('index'))

@app.route('/admin_remove_menu_item', methods = ["GET","POST"])
@login_required
def admin_remove_menu_item():
  form = RemoveMenuItemForm(request.values)
  if request.method == "POST":
    menu_item_id = form.food_id.data
    menu_item = db.session.query(MenuItem).filter(MenuItem.id == menu_item_id).one()
    db.session.delete(menu_item)
    db.session.commit()
    flash("Item removed for today's menu","success")
    return redirect(url_for("admin_add_menu_item"))
  else:
    return redirect(url_for("admin_add_menu_item"))

@app.route('/admin_add_existing_food', methods = ["GET","POST"])
@login_required
def admin_add_existing_food():
  exform = AddExistingFoodToMenu(request.values)
  if request.method == "POST":
    food_id = exform.food_id.data
    quantity = exform.quantities.data
    truck = db.session.query(Truck).filter(Truck.user_id == current_user.id).first()
    menu_item = db.session.query(MenuItem).filter(MenuItem.food_id == food_id,MenuItem.date == datetime.date(datetime.utcnow())).first()
    if truck:
      if menu_item:
        print menu_item.id
        print menu_item.max_quantity
        menu_item.max_quantity += int(quantity)
        menu_item.save()
        print quantity
        print menu_item.max_quantity
        print "saved"
      else:
        MenuItem(truck_id=truck.id, date=datetime.date(datetime.utcnow()), food_id=food_id, max_quantity = quantity).save()
        print "added"
      return redirect(url_for("admin_add_menu_item"))
    else:
      flash("You don't have permission to add menu", "error")
      return redirect(url_for('index'))
  else:
    return redirect(url_for("admin_add_menu_item"))